<template>
  <dd-container>
    <dd-card>
      <!-- 数据信息 -->
      <dd-table ref="dictTable"
                rowKey="id"
                :data="tableData"
                :option="option"
                :screen="searchForm"
                :loadingData="loadDictList"
                :treeProps="{children: 'childrens', hasChildren: 'hasChildren'}">
        <!-- 占位用的，解决展开收起跑到左边去的问题 -->
        <template slot="condition">
          <el-form-item></el-form-item>
        </template>
        <template slot="operation">
          <el-form-item>
            <el-button type="add" size="small" @click="openDialog('add', { enable: 1 })" v-if="showButton($route.path, '新增')">新增</el-button>
          </el-form-item>
        </template>
        <el-table-column prop="name" label="字典名称" width="200" align="start" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="code" label="字典编码" width="150" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="appName" label="程序名称" width="200" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="enable" label="启用状态" width="100" align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            {{(scope.row.enable == 1)? "是": (scope.row.enable == 0? "否" : "-")}}
          </template>
        </el-table-column>
        <el-table-column prop="key" label="关键字" width="200" align="center"></el-table-column>
        <el-table-column prop="valueType" label="字典类型" width="120" align="center">
          <template slot-scope="scope">
            {{ scope.row.valueType != undefined ? $enums.FIELD_TYPE.getLabelByValue(scope.row.valueType): '-'}}
          </template>
        </el-table-column>
        <el-table-column prop="value1" label="字典值" width="200" align="center"></el-table-column>
        <el-table-column label="操作" align="center" width="400" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="add" @click="openDialog('add', { enable: 1, level: 1, pId: scope.row.id })" :style="{visibility:(scope.row.dictId == null || scope.row.dictId == undefined) && showButton($route.path, '新增')?'visible':'hidden'}">添加节点</el-button>
            <el-button size="mini" type="add" @click="openDialog('addSub', scope.row)" :style="{visibility:(scope.row.dictId == null || scope.row.dictId == undefined) && showButton($route.path, '新增')?'visible':'hidden'}">添加项</el-button>
            <el-button size="mini" type="info" @click="openDialog('info', scope.row)" v-if="showButton($route.path, '详情')">详情</el-button>
            <el-button size="mini" type="edit" @click="openDialog('edit', scope.row)" v-if="showButton($route.path, '编辑')">编辑</el-button>
            <el-button size="mini" type="del" @click="handleDelete(scope.$index, scope.row)" v-if="showButton($route.path, '删除')">删除</el-button>
          </template>
        </el-table-column>
      </dd-table>
      <dict-mgr-handle-dialog :visible.sync="dictMgrHandleDialogVisible"
                              :modelType="modelType"
                              :modelData="modelData"
                              @loadList="loadDictList">
      </dict-mgr-handle-dialog>
      <field-mgr-handle-dialog :visible.sync="fieldMgrHandleDialogVisible"
                               :modelType="modelType"
                               :modelData="modelData"
                               @loadList="loadDictList">
      </field-mgr-handle-dialog>
    </dd-card>
  </dd-container>
</template>

<script>
import dictMgrHandleDialog from './dialog/dictMgrHandleDialog.vue'
import fieldMgrHandleDialog from './dialog/fieldMgrHandleDialog.vue'

import { mapGetters } from 'vuex'

export default {
  name: 'dictMgr',
  components: { dictMgrHandleDialog, fieldMgrHandleDialog},
  data() {
    return {
      searchForm: {
        name: '',
        pageIndex: 1,
        pageSize: 10,
      },
      tableData: [],
      option: {
        total: 0,
        loading: true,
        operation: true,
      },
      dictMgrHandleDialogVisible: false,
      fieldMgrHandleDialogVisible: false,
      modelType: '',
      modelData: {},
    }
  },
  computed: {
    ...mapGetters('ddAdmin/menu', ['showButton'])
  },
  async mounted() {
    this.loadDictList();
  },
  methods: {
    onSearch() {
      this.searchForm.pageIndex = this.$options.data().searchForm.pageIndex;
      this.loadDictList();
    },
    // 切分树状字典列表
    async loadDictList() {
      try {
        let allTreeData = {}, result = {};
        // 一次性获取所有数据
        result = await this.$api.dictInfo.list({ ...this.searchForm, pageIndex: 1, pageSize: 9999 });
        // 生成字典树
        allTreeData = this.dictTree(result.value);
        // 分页数量
        this.option.total = allTreeData.length;
        // 页数据
        this.tableData = allTreeData.slice((this.searchForm.pageIndex - 1) * this.searchForm.pageSize, (this.searchForm.pageIndex - 1) * this.searchForm.pageSize + this.searchForm.pageSize);
        // 载入完成
        this.option.loading = false;
        // 更新初始化字典
        await this.$store.dispatch('ddAdmin/dict/loadDict', false)
      } catch (error) {
        console.log(error);
        this.option.loading = false;
      }
    },
    // 生成字典子节点
    dictTree(list) {
      // 一级父菜单
      let parents = list.filter(item => item.dictId == null || item.dictId == undefined)
      // 生成父菜单
      function translator(parents) {
        // 查询每个父菜单子菜单
        parents.forEach( element => {
          if(!element.key){
            element.key = '-';
          }
          if(!element.value1){
            element.value1 = '-';
          }
          console.log(element);
          if (element.dictFieldss && element.dictFieldss.length > 0) {
            // 将子属性添加到字列表
            element.dictFieldss.forEach(item => {
              // 添加到父菜单儿子列表
              item.name = item.description;
              item.enable = element.enable;
              item.appName = element.appName;
              item.code = element.code;
              element.childrens ? element.childrens.push(item) : element.childrens = [item];
            });
          }

          if(element.childrens && element.childrens.length > 0){
            translator(element.childrens);
          }
        })
      }
      // 生成菜单树
      translator(parents);
      // 返回节点
      return parents;
    },
    openDialog(modelType, modelData) {
      this.modelType = modelType;
      this.modelData = modelData === undefined ? {} : JSON.parse(JSON.stringify(modelData));
      // 添加子项|编辑子项|删除子项
      if(modelData.dictId || modelType == 'addSub') {
        if(modelType == 'addSub') {
          this.modelType = 'add';
          this.modelData = {
            app: process.env.VUE_APP_SYSTEM_NAME,
            key: '',
            description: '',
            value1: '',
            dictId: modelData.id,
            enable: 1,
            valueType: 1,
          }
        }
        this.fieldMgrHandleDialogVisible = true;
        return ;
      }
      // 添加父项|编辑父项|删除父项
      this.dictMgrHandleDialogVisible = true;
    },
    handleDelete(index, row) {
      let ids = row.id, _this = this;
      console.log(ids)
      this.$confirm(`此操作将永久删除 ${row.name} 字典, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose(action, instance, done) {
          if (action == 'confirm') {
            if(row.dictId){
              this.$api.dictFields
              .deleteBatch({ ids })
              .then((res) => {
                this.$message.success('删除成功');
                done();
                _this.loadDictList();
                _this.$store.dispatch("ddAdmin/dict/loadDict", false, {root: true});
              })
              .catch((error) => {
                console.log(error);
              });
            } else {
              this.$api.dictInfo
              .deleteBatch({ ids })
              .then((res) => {
                this.$message.success('删除成功');
                done();
                _this.loadDictList();
              })
              .catch((error) => {
                console.log(error);
              });
            }
          } else {
            done();
          }
        },
      })
      .then(() => { })
      .catch((err) => {
        this.$message.info('已取消删除');
      });
    }
  },
}
</script>

<style lang="scss" scoped>
</style>
